<template>
    <!-- 权限分配 -->
    <!-- <el-dialog title="账号角色分配" :visible.sync="flag" :close-on-click-modal="false"> -->
    <!-- 
        $attrs ：没有被拦截的由父组件传递的属性，以对象方式存储
        $listeners ：由父组件传递的自定义事件，以对象方式存储

        v-bind=" Object " 一次性完成多个属性的绑定操作
        v-on=" Object " 一次性完成多个事件的绑定操作  v-on="{ click:fun,"update:flag":fun }"
    -->
    <el-dialog v-bind="$attrs" :visible.sync="flag" v-on="$listeners">
        <!-- 内容-star -->
        <el-form label-width="80px" :model="editUser" :rules="$rules.user" ref="form">
            <el-form-item label="当前用户">
                <el-input readonly :value="editUser.username"></el-input>
            </el-form-item>
            <el-form-item label="当前权限">
                <el-input readonly :value="editUser.role_name"></el-input>
            </el-form-item>
            <el-form-item label="新权限" prop="rid">
                <el-select placeholder="选择新权限" v-model="editUser.rid" style="width:100%">
                    <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <!-- 内容-end -->
        <template #footer>
            <el-button @click="flag=false">取 消</el-button>
            <el-button type="primary" @click="setUserRole()">确 定</el-button>
        </template>
    </el-dialog>
</template>

<script>
export default {
    data() {
        return {
            flag:false,
            editUser:{
                username:"",
                role_name:"",
                rid:""
            },
            roles:[]
        }
    },
    methods:{
        close(){
            this.flag = false;
        },
        open(){
            this.flag = true;
        },
        async loadAllRoles(){
            let roles = await this.$api.getAllRoles()
            // console.log(roles);
            if(roles){
                this.roles = roles
            }
        },
        async setUserRole(){
            try {
                await this.$refs.form.validate()
                let newRole = await this.$api.changeUserRole(this.editUser.id,this.editUser.rid)
                if(newRole){
                     this.$notify({
                        title: `"${this.editUser.username}"账号权限变更成功`,
                        type: 'success'
                    });
                    this.editUser = {
                        username:"",
                        role_name:"",
                        rid:""
                    }
                    this.close();
                    this.$emit("update:data");
                    this.$regs.form.clearValidate()
                }
            } catch (error) {
                console.log(error);
            }
        }
    },
    created(){
        this.loadAllRoles();
    }
}
</script>